<script setup lang="ts">
import type { DefTenantApplicationRelModel } from '#/api';

import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { ColPage } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { useFs } from '@fast-crud/fast-crud';
import { Button, Tooltip } from 'ant-design-vue';

import { DefTenantApplicationRelApi } from '#/api/devOperation/application/defTenantApplicationRel';
import { RouteEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';

import { createCrudOptions } from './data/grant-crud';
import ApplicationTrees from './modules/application-trees.vue';

defineOptions({
  name: '企业应用授权',
  inheritAttrs: false,
});

const colPageProps = reactive({
  leftCollapsedWidth: 3,
  // 左侧最大宽度百分比
  leftMaxWidth: 50,
  // 左侧最小宽度百分比
  leftMinWidth: 10,
  // 左侧默认宽度
  leftWidth: 50,
  // 右侧默认宽度
  rightWidth: 50,
  // 左侧可折叠
  leftCollapsible: true,
  // 显示拖动手柄
  splitHandle: true,
  // 可拖动调整宽度
  resizable: true,
  // 显示拖动分隔线
  splitLine: true,
});

const { crudRef, crudBinding, crudExpose, checkedRowKeys } = useFs({
  createCrudOptions,
});
const treesRef = ref();
const { push } = useRouter();
const { createMessage } = useMessage();

// 页面打开后获取列表数据
onMounted(async () => {
  crudExpose.doRefresh();
  treesRef.value.load();
});

async function handleSave(
  data: DefTenantApplicationRelModel.DefTenantApplicationRelSaveVO,
) {
  if (checkedRowKeys.value?.length > 0) {
    data.tenantIdList = checkedRowKeys.value;
    await DefTenantApplicationRelApi.grant(data);
    createMessage.success('授权成功');

    push({
      name: RouteEnum.APPLICATION_GRANT_MANAGE,
    });
  } else {
    createMessage.warning('请先勾选数据');
  }
}
</script>

<template>
  <ColPage v-bind="colPageProps">
    <template #left="{ isCollapsed, expand }">
      <div v-if="isCollapsed" @click="expand">
        <Tooltip title="点击展开左侧">
          <Button shape="circle" type="primary">
            <template #icon>
              <IconifyIcon class="text-2xl" icon="bi:arrow-right" />
            </template>
          </Button>
        </Tooltip>
      </div>
      <div
        v-else
        class="border-border bg-card mr-1 h-full rounded-[var(--radius)] border p-1"
      >
        <FsCrud ref="crudRef" v-bind="crudBinding" />
      </div>
    </template>
    <ApplicationTrees ref="treesRef" @save="handleSave" />
  </ColPage>
</template>

<style lang="scss">
.demo-nest {
  width: 100%;
  height: 100%;
}
</style>
